<?php
class AdminLoginController extends BaseController {
    public function IndexAction(){
        $this->assign('title', 'Login');
        $this->display();
    }

    public function LoginAction(){
        $error = '';
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $username = $_POST['username'];
            $password = $_POST['password'];
            $ip = 'Login-'.$_SERVER['REMOTE_ADDR'];
            $n = (int)Cache::get($ip);
            if($n>=3){
                $error = '你失败次数过多';
                goto End;
            }
            if ($this->_checkUser($username,$password)) {
                Cache::delete($ip);
                $_SESSION['username'] = $username;
                // 重定向回原始页面
                $url = isset($_GET['url']) ? $_GET['url'] : '/Admin/Home/Index';
                $this->redirect($url);
                exit();
            } else {
                Cache::set($ip,$n+1,900);
                $error = '账号或密码不正确';
            }
        }
        End:
        $this->assign('title', 'Login');
        $this->assign('error', $error);
        $this->display('index');
    }

    public function LogoutAction(){
        session_unset();
    }

    private function _checkUser($username,$password){
        $userModel = new UserModel();
        $member = $userModel->where(['username'=>$username])->get();
        if($member){
            return password_verify($password,$member['password']);
        }
        return false;
    }
}
